package com.laiketui.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laiketui.core.domain.Result;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.order.api.dto.OrderParentDTO;
import com.laiketui.order.api.enums.DelFlagEnum;
import com.laiketui.order.api.enums.OrderInvoiceEnum;
import com.laiketui.order.api.enums.TaxTypeEnum;
import com.laiketui.order.api.params.*;
import com.laiketui.order.domain.OrderParent;
import com.laiketui.order.service.OrderParentService;
import com.laiketui.order.service.OrderProcessService;
import com.laiketui.root.annotation.HttpApiMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

/**
 * (OrderParent)表控制层
 *
 * @author makejava
 * @since 2024-08-13 22:32:03
 */
@RestController
@RequestMapping("/orderParent/v2")
@Slf4j
public class OrderParentController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private OrderParentService orderParentService;
    @Autowired
    private OrderProcessService orderProcessService;

    /**
     * 分页查询所有数据
     *
     * @param page        分页对象
     * @param orderParent 查询实体
     * @return 所有数据
     */
    @GetMapping
    public Result selectAll(Page<OrderParent> page, OrderParent orderParent) {
        return Result.success(this.orderParentService.page(page, new QueryWrapper<>(orderParent)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result selectOne(@PathVariable Serializable id) {
        return Result.success(this.orderParentService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param orderParent 实体对象
     * @return 新增结果
     */
    @PostMapping
    public Result insert(@RequestBody OrderParent orderParent) {
        return Result.success(this.orderParentService.save(orderParent));
    }

    /**
     * 修改数据
     *
     * @param orderParent 实体对象
     * @return 修改结果
     */
    @PutMapping
    public Result update(@RequestBody OrderParent orderParent) {
        return Result.success(this.orderParentService.updateById(orderParent));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete(@RequestParam("idList") List<Long> idList) {
        LambdaQueryWrapper<OrderParent> orderWrapper = Wrappers.lambdaQuery();
        orderWrapper.in(OrderParent::getId, idList);
        OrderParent detail = new OrderParent();
        detail.setDeleted(DelFlagEnum.DELETED.getCode());
        return Result.success(this.orderParentService.update(detail, orderWrapper));
    }

    @PostMapping("/submitOrder")
    public OrderParentDTO getOrderList(@RequestBody @Validated UserPlaceOrderParams userPlaceOrderParams) {
        return this.orderParentService.submitOrder(userPlaceOrderParams, true);
    }

    @PostMapping("/placeOrder")
    @HttpApiMethod(urlMapping = {"app.orderV2.placeOrder"})
    public Result placeOrder(@Validated PlaceOrderParams orderVo) {
        if (OrderInvoiceEnum.YES.getCode().equals(orderVo.getInvoice())) {
            if (Objects.isNull(orderVo.getTaxType())) {
                return Result.error("请选择发票类型");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_PERSON.getCode().equals(orderVo.getTaxType()) && (StringUtils.isBlank(orderVo.getTaxName()) || StringUtils.isBlank(orderVo.getTaxCardNo()) || Objects.isNull(orderVo.getTaxAddress()) || Objects.isNull(orderVo.getTaxBank()) || Objects.isNull(orderVo.getTaxCardNo()) || Objects.isNull(orderVo.getTaxAccount()))) {
                return Result.error("请填写个人开票身份证和姓名");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_COMPANY_SPECIAL.getCode().equals(orderVo.getTaxType()) && (
                    Objects.isNull(orderVo.getTaxName()) ||
                            StringUtils.isBlank(orderVo.getOrganization())
                            || StringUtils.isBlank(orderVo.getTaxpayerNumber()))
            ) {
                return Result.error("请填写企业发票开票信息");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_COMPANY_SPECIAL.getCode().equals(orderVo.getTaxType()) &&
                    (
                            Objects.isNull(orderVo.getTaxName())
                                    || StringUtils.isBlank(orderVo.getOrganization())
                                    || StringUtils.isBlank(orderVo.getTaxAddress())
                                    || StringUtils.isBlank(orderVo.getTaxPhone())
                                    || StringUtils.isBlank(orderVo.getTaxAccount())
                                    || StringUtils.isBlank(orderVo.getTaxpayerNumber())
                                    || StringUtils.isBlank(orderVo.getTaxBank())
                    )
            ) {
                return Result.error("请填写完整增值发票开票信息");
            }
        }
        return Result.success(orderParentService.placeOrder(orderVo, getUser(orderVo)));
    }

    @PostMapping("/confirmOrder")
    @HttpApiMethod(urlMapping = {"app.orderV2.confirmOrder"})
    public Result confirmOrder(@Validated ConfirmOrderParams confirmOrderParams) {
        return Result.success(orderParentService.confirmOrder(confirmOrderParams, getUser(confirmOrderParams)));
    }

    @PostMapping("/orderInfo")
    @HttpApiMethod(urlMapping = {"app.orderV2.orderInfo"})
    public Result orderInfo(@Validated OrderInfoParams orderInfoParams) {

        return Result.success(orderParentService.orderInfo(orderInfoParams, getUser(orderInfoParams)));
    }

    @PostMapping("/orderList")
    @HttpApiMethod(urlMapping = {"app.orderV2.orderList"})
    public Result orderList(@Validated OrderParentListParams orderParentListParams) {

        return Result.success(orderParentService.orderList(orderParentListParams, getUser(orderParentListParams)));
    }

    @PostMapping("/orderDetail")
    @HttpApiMethod(urlMapping = {"app.orderV2.orderDetail"})
    public Result orderDetail(@Validated OrderInfoParams OrderInfoParams) {

        OrderParentDTO data = orderParentService.orderDetail(OrderInfoParams, getUser(OrderInfoParams));
        data.setSettlementAmount(BigDecimal.ZERO);
        data.setTotalCostPrice(BigDecimal.ZERO);
        data.getOrders().forEach(orderDTO -> {
            orderDTO.setSettlementAmount(BigDecimal.ZERO);
            orderDTO.setTotalCostPrice(BigDecimal.ZERO);
            orderDTO.getDetails().forEach(orderDetailDTO -> {
                orderDetailDTO.setCostPrice(BigDecimal.ZERO);
                orderDetailDTO.setSettlementPrice(BigDecimal.ZERO);
                orderDetailDTO.setTotalSettlementPrice(BigDecimal.ZERO);
            });
        });
        return Result.success(data);
    }

    //只能用作cloud内部调用不允许加@HttpApiMethod 否则没有校验权限会取消订单
    @PostMapping("/orderCancel")
    public Boolean orderCancel(@RequestBody @Validated CancelOrderInfoParams orderCancelParams) {
        return orderParentService.updateStatusCancel(orderCancelParams.getOrderParentNo(), orderCancelParams.getCancelReason());
    }

    @PostMapping("/buyAgain")
    @HttpApiMethod(urlMapping = {"app.orderV2.buyAgain"})
    public Result buyAgain(@Validated AgainConfirmOrderParams confirmOrderParams) {
        return Result.success(orderProcessService.buyAgainToCart(confirmOrderParams, getUser(confirmOrderParams)));
    }

    @PostMapping("/againConfirmOrder")
    @HttpApiMethod(urlMapping = {"app.orderV2.againConfirmOrder"})
    public Result againConfirmOrder(@Validated AgainConfirmOrderParams confirmOrderParams) {
        return Result.success(orderProcessService.againConfirmOrder(confirmOrderParams, getUser(confirmOrderParams)));
    }

    @PostMapping("/againPlaceOrder")
    @HttpApiMethod(urlMapping = {"app.orderV2.againPlaceOrder"})
    public Result againConfirmOrder(@Validated AgainPlaceOrderParams orderVo) {
        if (OrderInvoiceEnum.YES.getCode().equals(orderVo.getInvoice())) {
            if (Objects.isNull(orderVo.getTaxType())) {
                return Result.error("请选择发票类型");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_PERSON.getCode().equals(orderVo.getTaxType()) && (StringUtils.isBlank(orderVo.getTaxName()) || StringUtils.isBlank(orderVo.getTaxCardNo()) || Objects.isNull(orderVo.getTaxAddress()) || Objects.isNull(orderVo.getTaxBank()) || Objects.isNull(orderVo.getTaxCardNo()) || Objects.isNull(orderVo.getTaxAccount()))) {
                return Result.error("请填写个人开票身份证和姓名");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_COMPANY_SPECIAL.getCode().equals(orderVo.getTaxType()) && (
                    Objects.isNull(orderVo.getTaxName()) ||
                            StringUtils.isBlank(orderVo.getOrganization())
                            || StringUtils.isBlank(orderVo.getTaxpayerNumber()))
            ) {
                return Result.error("请填写企业发票开票信息");
            }
            if (TaxTypeEnum.INVOICE_TAX_TYPE_COMPANY_SPECIAL.getCode().equals(orderVo.getTaxType()) &&
                    (
                            Objects.isNull(orderVo.getTaxName())
                                    || StringUtils.isBlank(orderVo.getOrganization())
                                    || StringUtils.isBlank(orderVo.getTaxAddress())
                                    || StringUtils.isBlank(orderVo.getTaxPhone())
                                    || StringUtils.isBlank(orderVo.getTaxAccount())
                                    || StringUtils.isBlank(orderVo.getTaxpayerNumber())
                                    || StringUtils.isBlank(orderVo.getTaxBank())
                    )
            ) {
                return Result.error("请填写完整增值发票开票信息");
            }
        }
        return Result.success(orderProcessService.againPlaceOrder(orderVo, getUser(orderVo)));
    }

    @PostMapping("/cancelOrder")
    @HttpApiMethod(urlMapping = {"app.orderV2.cancelOrder"})
    public Result cancelOrder(@Validated OrderInfoParams orderInfoParams) {
        boolean cancelOrder = orderProcessService.cancelOrder(orderInfoParams.getOrderParentNo(), "自主取消，订单已取消");
        if (!cancelOrder) {
            return Result.error(ErrorCode.BizErrorCode.ERROR_CODE_DDGBSB, "取消失败");
        }
        return Result.success(cancelOrder);
    }


    @PostMapping("/export")
    @HttpApiMethod(urlMapping = {"app.orderV2.export"})
    public Result export(@Validated OrderInfoParams orderInfoParams, HttpServletResponse response) {
        Workbook workbook = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook = orderProcessService.export(orderInfoParams.getOrderParentNo());

            response.setContentType("application/msexcel");
            String title = String.format("订单%s.xls", orderInfoParams.getOrderParentNo());
            response.addHeader("Content-Disposition", "filename=" + URLDecoder.decode(title, GloabConst.Chartset.UTF8));
            workbook.write(outputStream);
            return null;
        } catch (Exception e) {
            log.error("导出失败", e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {

                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {

                }
            }
        }
        return Result.error("导出失败");
    }
}

